package com.demo.springboot底层演示.runListener;

import java.lang.reflect.Constructor;
import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.support.SpringFactoriesLoader;

public class Test {
	
	public static void main(String[] args) throws Exception {
		SpringApplication app = new SpringApplication(Test.class);
		app.addListeners(e -> System.out.println(e.getClass()));
		// 获取事件发送器实现类名
		List<String> names = SpringFactoriesLoader.loadFactoryNames(SpringApplicationRunListener.class, Test.class.getClassLoader());
		for (String name : names) {
			System.out.println(name);
			Class<?> clazz = Class.forName(name);
			Constructor<?> constructor = clazz.getConstructor(SpringApplication.class, String[].class);
			SpringApplicationRunListener publisher = (SpringApplicationRunListener)constructor.newInstance(app, args);
			
			// 发布事件
			publisher.starting(); // springboot开始启动
			publisher.environmentPrepared(new StandardEnvironment()); // 环境信息准备完毕
			GenericApplicationContext context = new GenericApplicationContext();
			publisher.contextPrepared(context); // 在spring容器创建，并调用初始化器之后，发送此事件
			publisher.contextLoaded(context); // 所有bean Definition加载完毕
			context.refresh();
			publisher.finished(context, new RuntimeException());
		}
	}

}
